var express = require('express');
var router = express.Router();

var UserToken = require('../db/user_tokens.js');
var cartDao = require('../dao/cart');
var cartRoutes = module.exports;

/**
 * 购物车详情列表
 * @param  token
 * @param  size
 * @param  page
 *         url/cart/list
 */
cartRoutes.list = function(req, res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('token不能为空！', 400));
    UserToken.checkAllLogin(par.token, null, function (err, errCode, userInfo) {
        if (err) {
            return res.json(new ERR(err, 400));
        }
        par.size = parseInt(par.size);
        if(!par.page) {
            par.start = 0;
        } else {
            par.start = (parseInt(par.page) - 1) * parseInt(par.size);
        }
        if(userInfo.isAdmin)  return res.json('账号或密码有误，请重试！' ,400);
        par.uid = userInfo.uid;
        cartDao.list(par, function(err, data){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/list', cartRoutes.list);

/**
 * 编辑购物车或加入购物车
 * @param  token
 * @param  num
 * @param  id   (传为编辑)
 * @param  gid  (编辑可不传)
 *         url/cart/save
 */
cartRoutes.save = function(req, res) {
    var par = req.body;
    console.log(par);
    if(!par.token) return res.json(new ERR('token不能为空！', 400));
    if(!par.num && parseInt(par.num) < 0) return res.json(new ERR('num不为空或num不合法！', 400));
    if(!par.id && !par.gid) return res.json(new ERR('id不能为空！', 400));
    UserToken.checkAllLogin(par.token, null, function (err, errCode, userInfo) {
        if (err) {
            return res.json(new ERR(err, 400));
        }
        if(userInfo.isAdmin)  return res.json('账号或密码有误，请重试！' ,400);
        par.uid = userInfo.uid;
        delete par.token;
        cartDao.save(par, function(err, data){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/save', cartRoutes.save);

/**
 * 删除购物车
 * @param  token
 * @param  idList
 *         url/cart/delete
 */
cartRoutes.delete = function(req, res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('token不能为空！', 400));
    if(!par.idList) return res.json(new ERR('idList或不能为空！', 400));
    UserToken.checkAllLogin(par.token, null, function (err, errCode, userInfo) {
        if (err) {
            return res.json(new ERR(err, 400));
        }
        if(userInfo.isAdmin)  return res.json('账号或密码有误，请重试！' ,400);
        par.uid = userInfo.uid;
        par.idList = JSON.parse(par.idList);
        cartDao.delete(par, function(err, data){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/delete', cartRoutes.delete);


module.exports = router;